package com.flyme.module.base.provider.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.flyme.common.core.constants.CommonConstants;
import com.flyme.common.core.model.ResultBody;
import com.flyme.common.core.model.query.PagerInfo;
import com.flyme.common.core.model.query.PqGrid;
import com.flyme.common.core.security.OpenHelper;
import com.flyme.common.core.security.OpenUserAuth;
import com.flyme.common.core.utils.ApiAssert;
import com.flyme.common.core.utils.ObjectUtils;
import com.flyme.common.core.utils.jpush.JpushPush;
import com.flyme.core.base.supper.controller.BaseController;
import com.flyme.core.base.supper.entity.EntityMap;
import com.flyme.core.base.utils.RedisUtils;
import com.flyme.module.base.client.dto.SysCreditbankDto;
import com.flyme.module.base.client.entity.*;
import com.flyme.module.base.client.enums.EducationEnum;
import com.flyme.module.base.provider.service.*;
import com.flyme.module.exam.client.entity.BusAbility;
import com.flyme.module.exam.provider.service.BusAbiltityService;
import com.flyme.module.file.client.entity.*;
import com.flyme.module.file.provider.service.*;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author flyme
 */
@Slf4j
@Api(tags = "app")
@RestController
@RequestMapping("/attention")
public class ApiAttentionController extends BaseController<BusAbiltityService, BusAbility> {

    @Autowired
    private SysColleconService colleconService;
    @Autowired
    private SysBalanceService balanceService;
    @Autowired
    private SysChargeconfigService chargeconfigService;
    @Autowired
    private SysCourseCommentService commentService;
    @Autowired
    private SysQuestionService questionService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysFeedbackService feedbackService;
    @Autowired
    private SysIntegralrecordService integralrecordService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private SysConfigService sysconfigService;
    @Autowired
    private SysCourseService courseService;
    @Autowired
    private SysLiveService liveService;
    @Autowired
    private SysOffCourseService sysOffCourseService;
    @Autowired
    private SysCataLogService catalogService;
    @Autowired
    private SysUsersturecordService usersturecordService;
    @Autowired
    private SysComplanService complanService;
    @Autowired
    private SysCreditbankService creditbankService;
    @Autowired
    private SysDictService dictService;
    @Autowired
    private SysAreaService areaService;
    @Autowired
    private SysPlanrecordService planrecordService;
    @Autowired
    private SysDeptService deptService;

    /**
     * /点赞，取消收藏/点赞
     *
     * @param type（1为普通课程2为在线直播3评论）
     * @param optType（1收藏2点赞）
     * @return type（1收藏2点赞3取消收藏4取消点赞）
     */
    @PostMapping(value = "/collecon")
    public ResultBody collecon(Long targetId, Integer type, Integer optType) {
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        Long userId = openUserAuth.getUserId();
        ApiAssert.notNull("参数不能为空", targetId, type, optType);
        String msg = "点赞";
        if (optType.equals(1)) {
            msg = "收藏";
        }
        Integer sucess = 3;
        SysCollecon collecon = colleconService.findCollecon(targetId, userId, type, optType);
        if (ObjectUtil.isNotNull(collecon)) {//取消收藏/点赞
            boolean a = colleconService.removeById(collecon.getId());
            if (optType.equals(2)) {
                sucess = 4;
            }
            return ResultBody.success(sucess).setInfo("取消" + msg + "成功");
        }
        collecon = new SysCollecon();
        collecon.setUserId(userId);
        collecon.setTargetId(targetId);
        collecon.setOptType(optType);
        collecon.setTargetType(type);
        colleconService.save(collecon);
        sucess = 2;
        if (optType.equals(1)) {
            sucess = 1;
        }
        return ResultBody.success(sucess).setInfo(msg + "成功");
    }

    /**
     * 删除收藏
     */
    @PostMapping(value = "/delCollecon")
    public ResultBody delCollecon(HttpServletResponse response, String ids) {
        ApiAssert.notNull("参数不能为空", ids);
        String[] idList = ids.split(",");
        for (String id : idList) {
            boolean flag = colleconService.removeById(id);
        }
        return ResultBody.ok("收藏删除成功");
    }

    /**
     * 余额充值配置表
     */
    @PostMapping(value = "/chargeconfig")
    public ResultBody chargeconfig(Integer type) {
        ApiAssert.notNull("参数不能为空", type);
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        Long userId = openUserAuth.getUserId();
        EntityMap map = new EntityMap();
        SysBalance balance = balanceService.findByUser(userId);
        List<SysChargeconfig> lists = chargeconfigService.selectByType(type);
        map.put("lists", lists);
        map.put("amount", balance.getAmount());
        return ResultBody.success(map);
    }

    /**
     * 发表评论
     * type:1一级评论2二级评论
     */
    @PostMapping(value = "/reply")
    public ResultBody reply(String content, String targetId, Integer type) {
        ApiAssert.notNull("参数不能为空", content, targetId, type);
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        String userId = String.valueOf(openUserAuth.getUserId());
        EntityMap map = new EntityMap();
        /*FilteredResult result = WordsFilterUtil.filterTextWithPunctation(content, '*');
        if(ObjectUtils.isNotEmpty(result.getBadWords())){
            return ResultBody.failed("您发表的内容中有违法关键字");
        }*/
        SysUser user = userService.getById(openUserAuth.getUserId());
        SysCourseComment comment = new SysCourseComment();
        comment.setCommentContent(Convert.strToUnicode(content));
        comment.setTargetId(targetId);
        comment.setReplyUserId(userId);
        comment.setReplyType(type);
        boolean a = commentService.save(comment);
        if (type.equals(2)) {//二级评论是向上级用户发推送
            SysCourseComment onComment = commentService.getById(targetId);
            JpushPush jPush = new JpushPush();
            Map<String, String> msg = new HashMap<String, String>();
            List<String> aliases = new ArrayList<>();
            aliases.add(onComment.getReplyUserId());
            String pushMsg = "您的评论有新的回复，请注意查看";
            //发送推送
            msg.put("msg", pushMsg);
            msg.put("pushType", "3");
            msg.put("content", pushMsg);
            msg.put("courseId", onComment.getTargetId());
            jPush.pushByAlias("COMM", aliases, pushMsg, "3", userId, msg);
        }
        if (a) {
            map.put("userId", user.getId());
            map.put("nickName", user.getNickName());
            map.put("avatar", user.getAvatar());
            map.put("replyId", comment.getId());
            map.put("showDate", DateUtil.date());
            map.put("replyContent", comment.getCommentContent());
        }
        return ResultBody.success(map);
    }

    /**
     * 在线客服页面
     */
    @PostMapping(value = "/onLineServicePage")
    public ResultBody onLineServicePage() {
        EntityMap map = new EntityMap();
        List<SysQuestion> list = questionService.selectAll();
        map.put("lists", list);
        return ResultBody.success(map);
    }

    /**
     * 常见问题
     */
    @PostMapping(value = "/issuePage")
    public ResultBody issuePage(HttpServletResponse response) {
        EntityMap map = new EntityMap();
        List<SysQuestion> list = questionService.selectAll();
        map.put("lists", list);
        return ResultBody.success(map);
    }

    /**
     * 留言反馈页面
     */
    @PostMapping(value = "/leaveWordPage")
    public ResultBody leaveWordPage(PagerInfo pagerInfo) {
        EntityMap map = new EntityMap();
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        SysUser accountInfo = userService.getById(openUserAuth.getUserId());
        List<EntityMap> list = feedbackService.selectByUser(String.valueOf(openUserAuth.getUserId()), pagerInfo);
        map.put("lists", list);
        map.put("userhead", accountInfo.getAvatar());
        feedbackService.editStatus(openUserAuth.getUserId());
        return ResultBody.success(map);
    }

    /**
     * 发布反馈
     */
    @PostMapping(value = "/sendFeedback")
    public ResultBody sendFeedback(String content) {
        ApiAssert.notNull("反馈内容不能为空", content);
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        SysFeedback feedback = new SysFeedback();
        feedback.setUserId(String.valueOf(openUserAuth.getUserId()));
        feedback.setContent(content);
        feedback.setType("1");
        feedback.setStatus(0);
        feedbackService.save(feedback);
        return ResultBody.ok("发布成功");
    }

    /**
     * 我的积分记录
     */
    @PostMapping(value = "/myIntegralRecord")
    public ResultBody myIntegralRecord(PagerInfo pagerInfo) {
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        EntityMap map = new EntityMap();
        SysBalance balance = balanceService.findByUser(openUserAuth.getUserId());
        map.put("integral", balance.getIntegral());
        List<EntityMap> list = integralrecordService.selectByUser(String.valueOf(openUserAuth.getUserId()), pagerInfo);
        map.put("records", list);
        return ResultBody.success(map);
    }

    /**
     * 换绑手机号
     */
    @PostMapping(value = "/changePhone")
    public ResultBody changePhone(String smsCode, String mobile) {
        ApiAssert.notNull("内容不能为空", smsCode, mobile);
        SysUser accountInfo = userService.findByMobile(mobile);
        if (ObjectUtils.isNotEmpty(accountInfo)) {//该手机号已注册
            return ResultBody.failed("该手机号已注册");
        }
        if (ObjectUtils.isNotEmpty(smsCode)) {
            String v = redisUtils.getString(CommonConstants.PRE_SMS + mobile);
            ApiAssert.notNull("验证码无效", v);
            ApiAssert.eq("验证码不正确", smsCode, v);
        }
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        boolean bang = userService.updateMobile(openUserAuth.getUserId(), accountInfo.getMobile(), mobile);
        if (bang) {
            return ResultBody.ok("手机号换绑成功");
        }
        return ResultBody.failed("手机号换绑失败");
    }

    /**
     * 我的计划页面
     */
    @PostMapping(value = "/myPlanPage")
    public ResultBody myPlanPage(PagerInfo pagerInfo) {
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        SysUser accountInfo = userService.getById(openUserAuth.getUserId());
        EntityMap map = new EntityMap();
        PqGrid pqGrid = complanService.selectUserPlan(accountInfo.getId(), accountInfo.getCompanyId(), accountInfo.getDeptId(), pagerInfo);
        List<EntityMap> list = (List<EntityMap>) pqGrid.getRows();
        for (EntityMap pu : list) {
            //计算所有课程总视频数量
            String[] courses = pu.get("courseIds").toString().split(",");
            List<EntityMap> plan = new ArrayList<>();
            for (String course : courses) {
                Long courseA = Long.valueOf(course);
                //计算该课程的视频数量
                Integer allNum = catalogService.countByCourseId(courseA);
                //计算用户该计划一共看了的视频数量
                Integer userNum = usersturecordService.countByCourse(openUserAuth.getUserId(), courseA);
                BigDecimal degree = new BigDecimal(userNum.toString()).divide(new BigDecimal(allNum.toString()), 2, BigDecimal.ROUND_HALF_UP);
                Long courseId = Long.valueOf(course);
                EntityMap em = new EntityMap();
                SysCourse uc = courseService.getById(course);
                em.put("degree", degree);
                em.put("courseTitle", uc.getCourseTitle());
                em.put("courseImage", uc.getCourseImage());
                em.put("courseCount", catalogService.countByCourseId(courseId));
                em.put("createTime", pu.get("createTime"));
                em.put("targetType", 2);
                em.put("id", pu.get("id"));//计划
                em.put("courseId", course);
                plan.add(em);
            }
            pu.put("course", plan);
            if(ObjectUtils.isNotEmpty(pu.get("deptIds"))){
                String[] ids = pu.get("deptIds").toString().split(",");
                List<String> deptList = deptService.selectByIds(ids);
                pu.put("deptIds", deptList);
            }else{
                pu.put("deptIds", new ArrayList<>());
            }
        }
        map.put("myPlans", list);
        planrecordService.editStatus(openUserAuth.getUserId());
        return ResultBody.success(map);
    }


    /**
     * 删除评论
     */
    @PostMapping(value = "/delComment")
    public ResultBody delComment(String commentId) {
        ApiAssert.notNull("内容不能为空", commentId);
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        SysCourseComment comment = commentService.getById(commentId);
        if (!comment.getReplyUserId().equals(String.valueOf(openUserAuth.getUserId()))) {
            return ResultBody.failed("非该评论用户，无法删除");
        }
        boolean j = commentService.delByUser(commentId);
        if (j) {
            return ResultBody.ok("评论删除成功");
        }
        return ResultBody.failed("评论删除失败");
    }

    public static void main(String[] args) {
        /*String str = "";
        str.replaceAll("<[.[^>]]*>", "");*/
        String A = "AAAAAAA";
        System.out.println(A);
        String B = A;
        System.out.println(B);
        B = "BBBBBBB";
        System.out.println(A);
    }

    /**
     * 分享接口
     * type：1课程2下载
     */
    @PostMapping(value = "/shareApp")
    public ResultBody shafreApp(String type, String courseId) {
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        EntityMap map = new EntityMap();
        if ("1".equals(type)) {
            SysCourse course = courseService.getById(courseId);
            map.put("title", "《" + course.getCourseTitle() + "》");
            String content = course.getCourseContent().replaceAll("<[.[^>]]*>", "");
            content = content.replaceAll("&nbsp;", "");
            map.put("subhead", "[勤博教育] " + content);
        }
        if ("2".equals(type) || "3".equals(type)) {
            map.put("title", "专业的人才培养，专业的课程教学，我们更专业");
            map.put("subhead", "海量的课程学习，专业的人才能力测评，给你最准确的自我定位。一切尽在勤·博教育");
        }
        if ("4".equals(type)) {
            SysLive live = liveService.getById(courseId);
            map.put("title", "《" + live.getLiveTitle() + "》");
            String content = live.getLiveContent().replaceAll("<[.[^>]]*>", "");
            content = content.replaceAll("&nbsp;", "");
            map.put("subhead", "[勤博教育] " + content);
        }
        if ("5".equals(type)) {
            SysOffCourse course = sysOffCourseService.getById(courseId);
            map.put("title", "《" + course.getCourseTitle() + "》");
            String content = course.getCourseContent().replaceAll("<[.[^>]]*>", "");
            content = content.replaceAll("&nbsp;", "");
            map.put("subhead", "[勤博教育] " + content);
        }
        map.put("url", "base/common/sharePage?type=" + type + "&courseId=" + courseId);
        //查询用户今天是否分享过，及是否分享超过100次
        String date = DateUtil.today();
        SysIntegralrecord ir = integralrecordService.findByDate(date, openUserAuth.getUserId());
        if(ObjectUtils.isNotEmpty(ir)){
            return ResultBody.success(map);
        }
        Integer sharNum = integralrecordService.countShare(openUserAuth.getUserId());
        if(sharNum >= 100){
            return ResultBody.success(map);
        }
        SysConfig sysconfig = sysconfigService.getByName("scoreShare");
        Integer integral = Integer.valueOf(sysconfig.getConfigVal());
        SysIntegralrecord integralrecord = new SysIntegralrecord();
        integralrecord.setAccountId(openUserAuth.getUserId());
        integralrecord.setRecordCode("scoreShare");
        integralrecord.setIntegral(integral);
        integralrecord.setRecordBody("分享");
        integralrecordService.save(integralrecord);
        SysBalance balance = balanceService.getById(openUserAuth.getUserId());
        balance.setIntegral(balance.getIntegral() + integral);
        balanceService.saveOrUpdate(balance);
        return ResultBody.success(map);
    }


    /**
     * 视频观看完成记录用户学习计划
     */
    @PostMapping(value = "/sendPlan")
    public ResultBody sendPlan(Long catalogId) {
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        SysUser user = userService.getById(openUserAuth.getUserId());
        SysCataLog catalog = catalogService.getById(catalogId);
        ApiAssert.notNull("视频不存在", catalog);
        //查询该用户是否存在该课程的学习计划
        Long courseId = catalog.getCourseId();
        PqGrid pqGrid = complanService.selectUserPlan2(user.getId(), user.getCompanyId(), user.getDeptId(), new PagerInfo(), courseId);
        if (pqGrid.getRows().size() < 1) {
            return ResultBody.failed("不存在该计划");
        }
        List<EntityMap> list = (List<EntityMap>) pqGrid.getRows();

        //当存在改学习计划后查询是否存在该视频记录
        for (EntityMap em : list) {
            Integer num = usersturecordService.countPlan(user.getId(), em.get("complanId"), catalogId);
            if (num < 1) {
                SysUsersturecord record = new SysUsersturecord();
                record.setCatalogId(catalogId);
                record.setComplanId(em.get("id"));
                record.setUserId(user.getId());
                record.setCourseId(Long.valueOf(catalog.getCourseId()));
                usersturecordService.save(record);
            }
        }
        return ResultBody.ok("学习计划更新成功");
    }

    /**
     * 查询学分状态
     */
    @PostMapping(value = "/checkScore")
    public ResultBody checkScore() {
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        EntityMap map = creditbankService.findByUser(openUserAuth.getUserId());
        EntityMap data = new EntityMap();
        data.put("isPass", 3);
        data.put("opinion", "");
        if (ObjectUtils.isNotEmpty(map)) {
            data.put("isPass", map.get("isPass"));
            data.put("opinion", map.get("opinion"));
        }
        return ResultBody.success(data);
    }

    /**
     * 用户学分页面
     */
    @PostMapping(value = "/scorePage")
    public ResultBody scorePage() {
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        EntityMap data = new EntityMap();
        EntityMap map = userService.findByUser(openUserAuth.getUserId());
        data.put("basic", map);
        //国籍
        List<Map<String, Object>> states = dictService.selectByCode("state");
        //民族
        List<Map<String, Object>> nation = dictService.selectByCode("nation");
        //教育程度
        List<EntityMap> educationList = EducationEnum.getList();
        //政治面貌
        List<Map<String, Object>> politics = dictService.selectByCode("politics");
        //城市
        List<Map<String, Object>> city = areaService.selectOne();
        data.put("educationList", educationList);//学历分类
        data.put("states", states);
        data.put("nation", nation);
        data.put("politics", politics);
        data.put("city", city);
        return ResultBody.success(data);
    }

    /**
     * 提交用户学分银行(基本信息)
     */
    @RequestMapping(value = "/updateCreditbank")
    public ResultBody updateCreditbank(SysCreditbankDto creditbank) {
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        if (ObjectUtils.isEmpty(creditbank.getUserId())) {//没有用户id时，新增
            creditbank.setUserId(openUserAuth.getUserId());
        }
        creditbank.setCardType("居民身份证");
        creditbank.setIsPass(3);
        SysUser user = userService.getById(openUserAuth.getUserId());
        user.setUserName(creditbank.getUserName());
        user.setEmail(creditbank.getEmail());
        user.setSex(creditbank.getSex());
        user.setPositionName(creditbank.getPositionName());
        user.setDeptName(creditbank.getDeptName());
        user.setAddress(creditbank.getAddress());
        user.setBirthday(creditbank.getBirthday());
        user.setCompany(creditbank.getCompany());
        user.setQq(creditbank.getQq());
        user.setId(openUserAuth.getUserId());
        boolean tag = creditbankService.saveOrUpdate(creditbank);
        userService.saveOrUpdate(user);
        return ResultBody.success(tag);
    }

    /**
     * 提交用户学分银行(证书信息)
     */
    @RequestMapping(value = "/subCertif")
    public ResultBody subCertif(SysCreditbankDto creditbank) {
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        SysCreditbank cb = creditbankService.getByUser(openUserAuth.getUserId());
        creditbank.setId(cb.getId());
        creditbank.setIsPass(0);
        boolean tag = creditbankService.saveOrUpdate(creditbank);
        return ResultBody.success(tag);
    }
}
